package binary_tree.leetcode.easy;

import linear_list.leetcode.easy.ListNode;

import java.util.ArrayList;
import java.util.List;

/**
 * @author bruin_du
 * @description 二叉搜索树的第k大节点
 * @date 2022/5/31 8:27
 **/
public class Offer54_KthLargest {
    int ret = 0,k = 0;
    public int kthLargest(TreeNode root, int k) {
        //方法一：使用辅助空间和中序遍历
        method1(root,k);

        //方法二：倒序中序遍历和计数
        this.k = k;
        method2(root);
        return ret;
    }

    private int method1(TreeNode root, int k) {
        List<Integer> list = new ArrayList<>();
        inOrder(list,root);
        return list.get(list.size() - k);
    }

    private void inOrder(List<Integer> list, TreeNode root) {
        if(root == null) return;
        inOrder(list, root.left);
        list.add(root.val);
        inOrder(list, root.right);
    }

    private void method2(TreeNode root) {
        if(root == null) return;
        method2(root.right);
        if(k == 0) return;
        if(--k == 0) ret = root.val;
        method2(root.left);
    }
}
